﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.SceneManagement;

public class UI_Mushroom : MonoBehaviour {

    float nowX;

    float startX;

    float tagetX;

    public Transform Target;

    public Text LoadingText;

    private AsyncOperation async;
    
    public float MaxTime=3f;

    private float nowTime = 0f;

    bool isLoaded = false;

    IEnumerator loadScene()
    {
        async = SceneManager.LoadSceneAsync("Level"+LevelManager.Instance.NowLevel.ToString());

        // 设置加载完成后不能自动跳转场景
        async.allowSceneActivation = false;
        // 下载完成后返回async
        yield return async;

    }

    private void Start()
    {
        StartCoroutine(loadScene());
        startX = nowX = transform.position.x;
        tagetX = Target.position.x;
    }

    private void FixedUpdate()
    {
        if (nowX == tagetX&&!isLoaded)
        {
            isLoaded = !isLoaded;
            StartCoroutine(Loaded());
        }
        else if(nowX == tagetX)
        {
            return;
        }
        Vector2 newPosition = transform.position;
        newPosition.x = nowX;
        transform.position = newPosition;
        LoadingText.text = ((int)((float)(nowX - startX)
            / (float)(tagetX - startX)*100)).ToString() + "%";
        nowX = Mathf.Lerp(startX, tagetX, async.progress*(nowTime/MaxTime)/0.9f);
        nowTime += Time.deltaTime;
    }

    IEnumerator Loaded()
    {
        yield return new WaitForSeconds(0.5f);
        async.allowSceneActivation = true;
    }

}
